package com.weipai.education.config.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 这个拦截器拦截所有的请求，主要 的作用就是现实每个接口的请求所耗费的时间
 */
public class ExcuteTimeInterceptor extends HandlerInterceptorAdapter {
	final static Logger log = LoggerFactory
			.getLogger(ExcuteTimeInterceptor.class);
	
	private NamedThreadLocal<Date> startTimeThreadLocal = new NamedThreadLocal<Date>("StopWatch-StartTime");  
	private static DateFormat sdf = new SimpleDateFormat("yyyyMMdd-HH:mm:ss:SSS");

	@Override
	public boolean preHandle(HttpServletRequest rquest, HttpServletResponse response,
                             Object obj) throws Exception {
		String originHeader=rquest.getHeader("Origin");
		if(null!=originHeader){
			response.setHeader("Access-Control-Allow-Origin", rquest.getHeader("Origin"));
			response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
			response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, " +
					"Content-Type, X-E4M-With,userId,token,Access-Control-Allow-Headers, user_type, Authentication-Token");
			response.setHeader("Access-Control-Allow-Credentials", "true");
			startTimeThreadLocal.set(new Date());//线程绑定变量（该数据只有当前请求的线程可见）
			return true;//继续流程
		}else{
			startTimeThreadLocal.set(new Date());//线程绑定变量（该数据只有当前请求的线程可见）
			return true;
		}
		//return false;
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object obj, Exception exception)
			throws Exception {
		Date endTime = new Date();//2、结束时间  
        Date beginTime = startTimeThreadLocal.get();//得到线程绑定的局部变量（开始时间）  
        long consumeTime = endTime.getTime() - beginTime.getTime();//3、消耗的时间
        log.info("请求:" + request.getRequestURI() + "，请求处理开始时间：" + sdf.format(beginTime) + "，请求处理结束时间：" + sdf.format(endTime)
				+ "，耗时：" + consumeTime + "毫秒");
	}
}
